<template>
	<view class="y-flex y-flex-1">
		<module-list
		ref="list"
		:data="components"
		:cell="cell"
		:bounce="pageStyle.enableBounce"
		:back-top-show="pageStyle.enableBackTop"
		:refreshImage="pageStyle.pulldownRefreshImage"
		:pulldownable="pageStyle.enablePulldown == 1"
		:loadmoreable="pageStyle.enableLoadmore == 1"
		:loadingColor="pageStyle.loadingColor"
		:backTopImage="pageStyle.backTopImage"
		:marginGap="pageStyle.pageMarginGap"
		:params="detail"
		@scroll="handleScroll"
		@pulldown="handlePulldown"
		@loaded="handleModuleLoaded">
			<template #top v-if="detail && detail.uniqueId">
				<cell v-if="items && items.length > 0">
					<view class="y-flex pt-30 pb-30 pl-30 pr-30 mt-30"
					:style="{'background-color': boxBgColor, 'margin-left': pageMarginGap, 'margin-right': pageMarginGap, 'border-radius': app.$utils.pixelunit(boxBorderRadius) }">
						<view class="y-flex y-row y-align-center find_novel_border pb-20" :style="{'border-bottom-color': skinColor.color_gap_1}">
							<text class="fs-35 y-flex-1 fw-bold" :style="{color: skinColor.color_1}">播放列表</text>
							<view class="y-flex y-row y-align-center" @tap="handleShowFullItems">
								<text class="fs-28" :style="{color: skinColor.color_3}">共{{items.length}}首</text>
								<com-icon name="right" size="32" :color="skinColor.color_3"></com-icon>
							</view>
						</view>
						<view class="y-flex">
							<view class="y-flex y-row y-align-center mt-30" v-for="(item, index) in items.slice(0, 5)" :key="index" @tap="playmusic(index)">
								<text class="fs-34 lines-1 y-flex-1 mr-10" :style="{color: skinColor.color_2}">{{item.title || detail.title + '第' + (index + 1) + '首'}}</text>
								<com-icon name="right" size="30" :color="skinColor.color_2"></com-icon>
							</view>
						</view>
					</view>
				</cell>
				<cell>
					<view class="y-flex pt-30 pb-20 pl-30 pr-30 mt-20"
					:style="{'background-color': boxBgColor, 'margin-left': pageMarginGap, 'margin-right': pageMarginGap,  'border-radius': app.$utils.pixelunit(boxBorderRadius)}">
						<com-image
						class="mb-20"
						:style="{'width': coverWidth ? app.$utils.pixelunit(coverWidth) : 'auto', 'height': app.$utils.pixelunit(coverHeight)}"
						:src="detail.cover" mode="aspectFill" v-if="detail.cover"></com-image>
						<view class="y-flex y-align-center">
							<text class="fs-40" :style="{color: skinColor.color_1}">{{detail.title}}</text>
							<text class="fs-24 mt-20" :style="{color: skinColor.color_3}" v-if="detail.subtitle">{{detail.subtitle}}</text>
						</view>
						<view elevation="5px" class="y-flex y-row y-align-center y-justify-center bg-error pt-20 pb-20 border-radius-50 mt-30" @tap="playmusic(record.current || 0, record.position || 0)">
							<view class="y-flex y-align-center" style="max-width: 400rpx;">
								<text class="fs-30 fr-fff">播放全部音频</text>
								<text class="fs-20 fr-eee mt-5 lines-1" v-if="record.id">上次播放到到 {{record.currentTitle}} </text>
							</view>
							<com-icon class="ml-20" name="video" size="45" :color="skinColor.color_white"></com-icon>
						</view>
						<com-read-more font-size="30" line-height="50" :color="skinColor.color_1" v-if="detail.description"></com-read-more>
						<scroll-view class="y-flex y-row y-align-center mt-20" :show-scrollbar="false" scroll-x v-if="detail.tags">
							<view class="find_novel_tag mr-20" v-for="(item, index) in detail.tags" :key="index" :style="{'border-color': themeColor}" @tap="handleTagTap(item)">
								<text class="fs-24" :style="{color: themeColor}">{{item.title}}</text>
							</view>
						</scroll-view>
						<mp-html class="mt-20" selectable :copy-link="false" :content="content" @linktap="handleLinkTap"></mp-html>
					</view>
				</cell>
			</template>
			<template #center v-if="showComment">
				<cell>
					<com-gap></com-gap>
					<view class="y-flex y-row y-align-center find_novel_border pb-20 pt-20 pl-20 pr-20"
					:style="{'border-bottom-color': skinColor.color_gap_1 ,'background-color': boxBgColor,'margin-left': pageMarginGap, 'margin-right': pageMarginGap}">
						<text class="fs-35 y-flex-1 fw-bold" :style="{color: skinColor.color_1}">评论列表</text>
					</view>
				</cell>
			</template>
		</module-list>
		<com-popup :visible.sync="fullItemsShow" direction="bottom">
			<view class="y-flex" :style="{'background-color': skinColor.color_bg_1, 'height': modalHeight + 'px'}">
				<view class="y-flex y-row y-align-center pt-20 pb-20 page-padding-gap border-bottom-1" :style="{'border-bottom-color': skinColor.color_gap_1}">
					<text class="fs-28 y-flex-1" :style="{color: skinColor.color_1}">选曲（{{items.length}}）</text>
					<com-icon name="close" size="40" :color="skinColor.color_2" @click="fullItemsShow = false"></com-icon>
				</view>
				<com-list class="y-flex-1">
					<cell v-for="(item, index) in items" :key="i">
						<view class="y-flex y-row y-align-center page-padding-gap pt-20 pb-20" @tap="playmusic(index)">
							<text class="fs-32 y-flex-1" :style="{color: skinColor.color_1}">{{item.title || detail.title + '第' + (index + 1) + '首'}}</text>
							<com-icon name="right" :color="skinColor.color_3" size="35"></com-icon>
						</view>
					</cell>
				</com-list>
				<com-gap></com-gap>
			</view>
		</com-popup>
	</view>
</template>

<script>
	import ModuleList from '../components/ModuleList.vue'
	import { openDB, closeDB, select, insert, remove } from '@/assets/database'
	export default {
		inject: ['getSkinColor', 'getPage', 'getBoxBgColor', 'getPageStyle', 'navigate', 'getQuery'],
		components: {
			ModuleList
		},
		computed: {
			autoplay () {
				return this.$store.getters['setting/GET_AUDIO_AUTOPLAY']
			},
			skinColor () {
				return this.getSkinColor()
			},
			//路由参数
			query () {
				return this.getQuery()
			},
			app () {
				return getApp().globalData
			},
			page () {
				return this.getPage()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			components () {
				return this.page?.components || []
			},
			cell () {
				return Object.assign({}, this.page?.comments || {}, {style: {cellName: 'comment-cell', cellGap: 0}})
			},
			boxBgColor () {
				return this.getBoxBgColor()
			},
			boxBorderRadius () {
				return this.pageStyle.componentBorderRadius
			},
			coverWidth () {
				return this.pageStyle.coverWidth || ''
			},
			coverHeight () {
				return this.pageStyle.coverHeight || 242
			},
			network () {
				return this.$store.getters['network/GET']
			},
			//页面左右边距
			pageMarginGap () {
				return this.app.$utils.pixelunit(this.pageStyle?.pageMarginGap)
			},
			//主题色
			themeColor () {
				return this.pageStyle.themeColor || this.skinColor.color_blue
			},
			content () {
				return `<div style="color: ${this.skinColor.color_1}">` + this.detail.content + '</div>'
			},
			sliderValue () {
				return (this.currentTime / this.duration) * 100
			}
		},
		data () {
			return {
				detail: {},//详情信息
				items: [],//分集列表
				showComment: false,//显示评论列表
				fullItemsShow: false,//展示完整剧集
				modalHeight: 0,//高度
				current: 0,//当前播放索引
				record: {}//历史记录
			}
		},
		mounted () {
			this.$nextTick(this.handlePulldown)
		},
		methods: {
			onShow () {
				if ( this.detail.uniqueId ) this.getRecord()
			},
			onBackPress () {
				if ( this.fullItemsShow ) {
					this.fullItemsShow = false
					return true
				}
				return false
			},
			async getRecord () {
				try{
					await openDB()
					const data1 = await select('record', 'unique_id = "' + this.detail.uniqueId + '"')
					this.record = data1.list[0] || {}
					const data2 = await select('collection', 'unique_id = "' + this.detail.uniqueId + '"')
					const utils = [{
						label: data2.count > 0 ? '已收藏' : '点击收藏',
						icon: data2.count > 0 ? 'favor_fill' : 'favor',
						color: data2.count > 0 ? this.skinColor.color_red : '',
						func: async () => {
							try{
								await openDB()
								if ( data2.count > 0 ) {
									await remove('collection', 'id = ' + data2.list[0].id)
									uni.showToast({
										title: '取消收藏成功',
										icon: 'none'
									})
									await closeDB()
									this.getRecord()
								} else {
									const params = {
										unique_id: this.detail.uniqueId,
										url: this.detail.url,
										title: this.detail.title || '',
										cover: this.detail.cover || '',
										is_adult: this.detail.isAdult || 0,
										source_id: this.detail.sourceId
									}
									await insert('collection', params)
									uni.showToast({
										title: '收藏成功',
										icon: 'none'
									})
									await closeDB()
									this.getRecord()
								}
							}catch(e){
								closeDB()
								uni.showToast({
									title: e.message,
									icon: 'none'
								})
							}
						}
					}]
					if ( this.detail.shareUrl && this.detail.title ) {
						utils.push({
							label: '分享资源',
							icon: 'forward',
							func: () => {
								this.app.$Router.push({
									path: '/pages/find/modules/poster',
									animationType: 'none',
									query: {
										params: this.detail
									}
								})
							}
						})
					}
					this.$emit('utils', utils)
				}catch(e){
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
				}
				closeDB()
			},
			handleScroll (e) {
				this.$emit('scroll', Math.abs(e.contentOffset.y))
			},
			handleTagTap (item) {
				this.navigate(item.url)
			},
			playmusic (current, start) {
				const list = this.items.map(item => Object.assign({}, {query: this.query, detail: this.detail, item, context: this.page?.context || {}, lyric: this.page?.lyric || {}}))
				this.$store.dispatch('audio/replace', list)
				this.$nextTick(function () {
					this.$store.dispatch('audio/change', current)
					this.app.$Router.push({
						path: '/pages/find/audio/player',
						animationType: 'fade-in'
					})
				})
			},
			handleLinkTap (e) {
				this.app.$Router.push({
					path: '/pages/browser/index',
					query: {src: e.href}
				})
			},
			handleModuleLoaded () {
				this.$emit('loaded', true)
				this.$refs.list && this.$refs.list.pulldownSuccess()
				this.showComment = (this.$refs.list?.cells?.length || 0) > 0
			},
			async handlePulldown (callback) {
				try{
					this.detail = await this.handleGetDetail()
					this.items = await this.handleGetItems()
					this.$nextTick(function () {
						this.$refs.list && this.$refs.list.initModule(callback)
						if ( this.detail.uniqueId ) this.getRecord()
					})
				}catch(e){
					this.$emit('loaded', true)
				}
			},
			async handleGetDetail () {
				const detail = this.page?.detail || {}
				const staticData = this.network.staticDataHandle(detail.staticData || {}, this.query)
				const dynamicData = detail.dynamicData
				const request = detail.request
				let data = {}
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
					data.uniqueId = data.id || this.network.getUniqueId(newRequest)
					if ( !data.shareUrl && !staticData.shareUrl ) data.shareUrl = await this.network.getShareUrl(newRequest)
				}
				return Object.assign({}, staticData, data)
			},
			async handleGetItems () {
				const items = this.page?.items || {}
				const params = Object.assign({}, this.query, this.detail)
				const staticData = items.staticData ? this.network.staticDataHandle(items.staticData, params) : []
				const dynamicData = items.dynamicData
				const request = items.request
				let data = []
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, params)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
				}
				return staticData.concat(data).map(s => Object.assign({}, s, { loading: false, isLive: s.isLive == 1 ? true : s.isLive == 0 ? false : s.isLive }))
			},
			handleShowFullItems () {
				const system = uni.getSystemInfoSync()
				this.modalHeight = system.windowHeight * (2 / 3)
				this.fullItemsShow = true
			}
		}
	}
</script>

<style>
	.find_novel_cover {
		width: 228rpx;
		height: 322rpx;
	}
	.find_novel_border {
		border-bottom-width: 1px;
		border-bottom-style: dashed;
	}
	.find_novel_tag {
		border-width: 1px;
		border-style: solid;
		border-radius: 5rpx;
		padding: 4rpx 10rpx;
	}
</style>